package com.szh.consumer.lister;

import com.rabbitmq.client.Channel;
import com.szh.common.constant.MQConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

/** V1
 * todo 注意 MQ 已经修改为手动ACK了
 * 测试提交 
 * */
@Component
@Slf4j
public class V1Lister {
 

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = MQConstant.DIRECT_QUEUE1_NAME),
            exchange = @Exchange(name = MQConstant.DIRECT_EXCHANGE_NAME, type = ExchangeTypes.DIRECT),
            key = {"red", "blue"}
    ))
    public void listenDirectQueue1(String msg) {
        log.info("收到消息队列1：{}", msg);
    }

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = MQConstant.DIRECT_QUEUE2_NAME),
            exchange = @Exchange(name = MQConstant.DIRECT_EXCHANGE_NAME, type = ExchangeTypes.DIRECT),
            key = {"red", "blue"},arguments = {}
    ))
    public void listenDirectQueue2(String msg) {
        log.error("收到消息队列2：{}", msg);
    }


    @RabbitListener(queues = {MQConstant.DELAY_QUEUE_NAME})
    public void delayQueueTest(String msg) {
        log.info("接受的-延迟队列消息-handleMsg,{}", msg);
    }


    @RabbitListener(queues = {MQConstant.HELLO_JAVA_QUEUE})
    public void simpleHello(Message message, Channel channel)  {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            String msg = new String(message.getBody());

            // 测试 手动NACK 。以及测试重复消费的问题
            log.error("MQ-简单工作模式-消费者-{},deliveryTag-{}",msg,deliveryTag);
            int flag = 0;
            if (flag==1){
                throw new RuntimeException("消费消息失败deliveryTag:"+deliveryTag);
            }
           channel.basicAck(deliveryTag,false);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("消费消息失败deliveryTag-{}",deliveryTag);
            try {
                channel.basicNack(deliveryTag,false,true);
            } catch (IOException ex) {
                log.error("重新入 MQ失败");
            }
        }
    }

}
